<template>
  <div class="article-list">
    <SearchBar @search="handleSearch" />
    <LoadingWrapper :loading="loading">
      <el-empty v-if="!articles.length" description="暂无数据" />
      <template v-else>
        <el-row :gutter="20">
          <el-col v-for="article in articles" :key="article.id" :span="8">
            <el-card class="article-card">
              <template #header>
                <div class="card-header">
                  <h3 class="article-title" @click="handleClick(article)">{{ article.title }}</h3>
                  <div class="operations">
                    <el-button-group>
                      <el-button 
                        type="primary" 
                        link
                        :loading="article.analyzing"
                        @click.stop="handleAnalyze(article)"
                      >
                        <el-icon><Reading /></el-icon>分析
                      </el-button>
                      <el-button 
                        type="success" 
                        link
                        @click.stop="handleViewQA(article)"
                      >
                        <el-icon><ChatDotSquare /></el-icon>问答
                      </el-button>
                    </el-button-group>
                    <el-button type="primary" link @click.stop="handleEdit(article)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="danger" link @click.stop="handleDelete(article)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
              <div class="article-content" @click="handleClick(article)">
                <p class="article-desc">{{ article.content?.substring(0, 100) }}...</p>
                <div class="article-footer">
                  <el-tag size="small" v-if="article.category">{{ article.category }}</el-tag>
                  <span class="article-time">{{ formatDate(article.createTime) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        
        <ArticleQAList
          v-model="qaDialogVisible"
          :article-id="currentArticleId"
          :title="currentArticleTitle"
        />
      </template>
      
      <!-- 添加编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="80%"
        :fullscreen="false"
        :close-on-click-modal="false"
        @close="resetForm"
      >
        <el-form :model="form" label-width="80px">
          <el-form-item label="标题" required>
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="内容" required>
            <div class="markdown-editor">
              <MdEditor
                v-model="form.content"
                :height="400"
                :toolbars="toolbars"
                @save="handleSave"
              />
            </div>
          </el-form-item>
          <el-form-item label="分类">
            <el-select
              v-model="form.category"
              placeholder="请选择分类"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="category in store.categories"
                :key="category"
                :label="category"
                :value="category"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签">
            <el-select
              v-model="form.tags"
              multiple
              collapse-tags
              placeholder="请选择标签"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="tag in store.tags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </LoadingWrapper>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useArticleStore } from '@/stores/article'
import type { Article, ArticleQuery } from '@/api/types'
import { formatDate } from '@/utils/format'
import { handleError } from '@/utils/error-handler'
import LoadingWrapper from '@/components/LoadingWrapper.vue'
import SearchBar from './SearchBar.vue'
import { 
  Edit,
  Delete,
  Reading,
  ChatDotSquare
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { analyzeArticle } from '@/api/analysis'
import ArticleQAList from './ArticleQAList.vue'

// 配置编辑器工具栏
const toolbars = [
  'bold',
  'underline',
  'italic',
  'strikethrough',
  '-',
  'title',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  '-',
  'preview',
  'fullscreen',
  '-',
  'save'
]

const router = useRouter()
const store = useArticleStore()

// 分页参数
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const loading = ref(false)

// 查询参数
const queryParams = ref<ArticleQuery>({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
  category: '',
  tags: []
})

// 文章列表
const articles = ref<Article[]>([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogTitle = computed(() => dialogType.value === 'add' ? '新增文章' : '编辑文章')

// 表单数据
const form = ref({
  id: '',
  title: '',
  content: '',
  category: '',
  tags: [] as string[]
})

// 加载文章列表
async function fetchData(params?: Partial<ArticleQuery>) {
  loading.value = true
  try {
    const mergedParams = {
      ...queryParams.value,
      ...params,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await store.fetchArticles(mergedParams)
    // 检查响应数据结构
    if (response?.data?.records) {
      articles.value = response.data.records
      total.value = response.data.total
    } else {
      articles.value = []
      total.value = 0
      console.error('Invalid response data structure:', response)
    }
  } catch (error) {
    handleError(error)
    articles.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearch(params: { keyword: string; category: string; tags: string[] }) {
  currentPage.value = 1
  queryParams.value = {
    ...queryParams.value,
    ...params
  }
  fetchData()
}

// 分页处理
function handleSizeChange(val: number) {
  pageSize.value = val
  fetchData()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  fetchData()
}

// 点击文��
function handleClick(article: Article) {
  router.push(`/article/${article.id}`)
}

// 编辑文章
function handleEdit(article: Article) {
  dialogType.value = 'edit'
  form.value = {
    id: article.id,
    title: article.title,
    content: article.content,
    category: article.category,
    tags: article.tags ? article.tags.split(',') : []
  }
  dialogVisible.value = true
}

// 删除文章
async function handleDelete(article: Article) {
  try {
    await ElMessageBox.confirm('确认删除该文章吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用删除 API
    await store.deleteArticle(article.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      handleError(error)
    }
  }
}

// 保存文章
async function handleSave() {
  try {
    const data = {
      ...form.value,
      tags: form.value.tags.join(',')
    }
    if (dialogType.value === 'edit') {
      await store.updateArticle(data)
      ElMessage.success('更新成功')
    } else {
      await store.createArticle(data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    handleError(error)
  }
}

// 重置表单
function resetForm() {
  form.value = {
    id: '',
    title: '',
    content: '',
    category: '',
    tags: []
  }
}

// 初始化
onMounted(async () => {
  try {
    await Promise.all([
      store.fetchCategories(),
      store.fetchTags()
    ])
  } catch (error) {
    handleError(error)
  }
  fetchData()
})

const qaDialogVisible = ref(false)
const currentArticleId = ref<number>(0)
const currentArticleTitle = ref('')

// 处理分析按钮点击
async function handleAnalyze(article: Article) {
  article.analyzing = true
  try {
    await analyzeArticle(article.id)
    ElMessage.success('分析完成')
    // 重新加载文章列表以更新分类和标签
    await fetchData()
  } catch (error) {
    handleError(error)
  } finally {
    article.analyzing = false
  }
}

// 查看问答
function handleViewQA(article: Article) {
  currentArticleId.value = article.id
  currentArticleTitle.value = article.title
  qaDialogVisible.value = true
}
</script>

<style scoped lang="scss">
.article-list {
  padding: 20px;
  
  .article-card {
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }
  }
  
  .article-content {
    padding: 14px;
  }
  
  .article-title {
    margin: 0;
    font-size: 16px;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .article-desc {
    font-size: 14px;
    color: #909399;
    margin: 10px 0;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
  
  .article-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }
  
  .article-time {
    font-size: 13px;
    color: #909399;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .article-title {
    margin: 0;
    font-size: 16px;
    color: #303133;
    cursor: pointer;
    
    &:hover {
      color: #409eff;
    }
  }

  .operations {
    display: flex;
    gap: 8px;
    align-items: center;
    
    .el-button-group {
      margin-right: 8px;
    }
  }

  .article-content {
    cursor: pointer;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .markdown-editor {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    
    :deep(.md-editor) {
      border: none;
    }
  }

  :deep(.el-dialog) {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: 90vh;
    max-width: 90vw;
    
    .el-dialog__body {
      flex: 1;
      overflow: auto;
      padding: 20px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px;
  }
}
</style>